import { defineComponent } from 'vue';

import BpmnModdle from 'bpmn-moddle';
import modeler from '/@/store/modules/bpmnModeler';
import { Button, Popover } from 'ant-design-vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { Icon } from '/@/components/Icon';

import { useMessage } from '/@/hooks/web/useMessage';
import { CodeEditor, MODE } from '/@/components/CodeEditor';

const Previews = defineComponent({
  name: 'Previews',
  setup() {
    const { t } = useI18n();
    // const previewModel = useDialog();
    const modelerStore = modeler();
    const { createMessage, createConfirm } = useMessage();

    const moddle = new BpmnModdle();

    const openXMLPreviewModel = async () => {
      try {
        const modeler = modelerStore.getModeler!;

        if (!modeler) {
          return createMessage.warning('模型加载失败，请刷新重试');
        }

        const { xml } = await modeler.saveXML({ format: true, preamble: true });

        createConfirm({
          iconType: 'info',
          width: '75%',
          title: t('routes.bpmn.previewAs'),
          content: () => (
            <div class="preview-model">
              <CodeEditor mode={MODE.XML} value={xml}></CodeEditor>
            </div>
          ),
        });
      } catch (e) {
        createMessage.error((e as Error).message || (e as string));
      }
    };

    const openJsonPreviewModel = async () => {
      const modeler = modelerStore.getModeler!;

      if (!modeler) {
        return createMessage.warning('模型加载失败，请刷新重试');
      }

      const { xml } = await modeler.saveXML({ format: true });

      const jsonStr = await moddle.fromXML(xml!);
      createConfirm({
        iconType: 'info',
        width: '75%',
        title: t('routes.bpmn.previewAs'),
        content: () => (
          <div class="preview-model">
            <CodeEditor mode={MODE.JSON} value={JSON.stringify(jsonStr, null, 2)}></CodeEditor>
            {/* <NCode code={JSON.stringify(jsonStr, null, 2)} language="json" wordWrap={true}></NCode> */}
          </div>
        ),
      });
    };

    return () => (
      <div className="hl-group-item">
        <Popover
          v-slots={{
            content: () => (
              <div class="button-list_column">
                <Button type="dashed" onClick={openXMLPreviewModel}>
                  {t('routes.bpmn.previewAsXML')}
                </Button>
                <Button type="dashed" onClick={openJsonPreviewModel}>
                  {t('routes.bpmn.previewAsJSON')}
                </Button>
              </div>
            ),
          }}
        >
          {/* <Button type="primary">{t('routes.bpmn.previewAs')}</Button> */}
          {/* <Icon icon="basil:eye-outline" /> */}
          <Button class="mr-2" type="link">
            <Icon icon="basil:eye-outline" />
            预览
          </Button>
        </Popover>
      </div>
    );
  },
});

export default Previews;
